package com.lagou.rpcproviderspringboot.framework.handler;

import com.lagou.protocol.RpcRequest;
import com.lagou.protocol.RpcResponse;
import com.lagou.protocol.serializer.Serializer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {
    /**
     * 服务映射表
     */
    private Map<String, Object> serviceMap;

    /**
     * 序列化器
     */
    private Serializer serializer;

    /**
     * 构造UserServiceHandler对象
     *
     * @param serviceMap 服务映射表
     * @param serializer 序列化器
     */
    public UserServiceHandler(Map<String, Object> serviceMap, Serializer serializer) {
        this.serviceMap = serviceMap;
        this.serializer = serializer;
    }

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest) msg;
        Object service = serviceMap.get(rpcRequest.getClassName());
        if (service == null) {
            ctx.close();
            return;
        }

        Method method = service.getClass()
                .getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object result = method.invoke(service, rpcRequest.getParameters());

        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setClassName(result.getClass().getName());
        rpcResponse.setContent(serializer.serialize(result));

        ctx.writeAndFlush(rpcResponse);
    }
}
